package com.cg.service;

import com.alibaba.fastjson.JSON;
import com.cg.common.KeyCommon;
import com.cg.util.TokenUtil;
import com.cg.vo.LoginUserVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName UserTokenServiceImpl
 * @Description TODO
 * @Author CG
 * @Date 2023/12/6 11:15
 **/
public class UserTokenServiceImpl implements UserTokenService {

    @Resource
    private RedisTemplate<String,String> redisTemplate;

    @Value("${userTokenTimeOut}")
    private Long userTokenTimeOut;

    @Override
    public void setUserToken(LoginUserVo loginUserVo) {
        //生成Token
        String token = TokenUtil.createToken(loginUserVo);
        //生成value
        loginUserVo.setToken(token);
        //需要将对象转换成json
        String value = JSON.toJSONString(loginUserVo);
        redisTemplate.opsForValue().set(token,value,userTokenTimeOut, TimeUnit.SECONDS);
    }

    @Override
    public LoginUserVo getUserByToken(String token) {
        //先根据Token获取
        String json = redisTemplate.opsForValue().get(token);
        if(json == null || json.equals("")){
            return null;
        }
        LoginUserVo loginUserVo = JSON.parseObject(json, LoginUserVo.class);
        return loginUserVo;
    }

    @Override
    public void deleteByToken(String token) {
        redisTemplate.delete(token);
    }

    //删除所有的keys
    @Override
    public void deleteTokens() {
        //获取所有的userToken的key
        Set<String> keys = redisTemplate.keys(KeyCommon.USER_TOKEN_KEY + "*");
        //删除
        redisTemplate.delete(keys);
    }
}
